/**
 * 重复点击
 * @description 按住绑定节点后间隔100~200毫秒触发一次
 * @example
 * <div v-repeat-click="callback" />
 */
import { isFunction } from 'lodash';
import { once } from 'tdesign-vue-next/lib/utils/dom';
import { Directive, DirectiveBinding } from 'vue';

import { isMac } from '@/utils';

const repeatClick: Directive = {
  mounted(el: HTMLElement, bindin: DirectiveBinding) {
    let interval: any = null;
    let startTime: number;
    const maxIntervals = isMac() ? 100 : 200;
    const handler = () => {
      if (isFunction(bindin.value)) bindin.value();
    };
    const clear = () => {
      if (Date.now() - startTime < maxIntervals) {
        handler();
      }
      clearInterval(interval);
      interval = null;
    };

    useEventListener(el, 'mousedown', (e: { button: number }) => {
      if (e.button !== 0) return;
      startTime = Date.now();
      once(document, 'mouseup', clear);
      clearInterval(interval);
      interval = setInterval(handler, maxIntervals);
    });
  }
};

export default repeatClick;
